import React from "react";
import { Link, useLocation } from "react-router-dom";
import { RouteConfig } from "../../router/types";
import "./Breadcrumb.css";

interface BreadcrumbProps {
  routes: RouteConfig[];
  separator?: React.ReactNode;
}

/**
 * 面包屑导航组件
 */
const Breadcrumb: React.FC<BreadcrumbProps> = ({ routes, separator = "/" }) => {
  const location = useLocation();
  const pathSnippets = location.pathname.split("/").filter((i) => i);

  // 构建面包屑项
  const buildBreadcrumbItems = () => {
    const breadcrumbItems: { path: string; title: string }[] = [];
    let currentPath = "";

    // 添加首页
    breadcrumbItems.push({ path: "/", title: "首页" });

    // 根据当前URL路径构建面包屑
    pathSnippets.forEach((snippet) => {
      currentPath += `/${snippet}`;

      // 在路由配置中查找匹配项
      const matchedRoute = findRouteByPath(routes, currentPath);

      if (matchedRoute && !matchedRoute.meta?.hideInBreadcrumb) {
        breadcrumbItems.push({
          path: currentPath,
          title: matchedRoute.meta?.title || snippet,
        });
      }
    });

    return breadcrumbItems;
  };

  // 递归查找路由
  const findRouteByPath = (
    routes: RouteConfig[],
    path: string
  ): RouteConfig | undefined => {
    for (const route of routes) {
      const routePath = route.path === "" ? "/" : route.path;
      const fullPath = routePath.startsWith("/") ? routePath : `/${routePath}`;

      if (fullPath === path) {
        return route;
      }

      if (route.children) {
        const childRoute = findRouteByPath(route.children, path);
        if (childRoute) {
          return childRoute;
        }
      }
    }

    return undefined;
  };

  const breadcrumbItems = buildBreadcrumbItems();

  if (breadcrumbItems.length <= 1) {
    return null;
  }

  return (
    <nav aria-label="breadcrumb" className="breadcrumb-nav">
      <ol className="breadcrumb-list">
        {breadcrumbItems.map((item, index) => {
          const isLast = index === breadcrumbItems.length - 1;

          return (
            <li
              key={item.path}
              className={`breadcrumb-item ${isLast ? "active" : ""}`}
            >
              {isLast ? (
                <span>{item.title}</span>
              ) : (
                <>
                  <Link to={item.path}>{item.title}</Link>
                  <span className="breadcrumb-separator">{separator}</span>
                </>
              )}
            </li>
          );
        })}
      </ol>
    </nav>
  );
};

export default Breadcrumb;
